package com.kaesar.leetcode.LeetCode_301_350;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class LeetCode_349 {
    public static int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> firstNums = new HashSet<>();
        for (int i : nums1) {
            firstNums.add(i);
        }
        int[] result = new int[nums1.length];
        int index = 0;
        Set<Integer> secondNums = new HashSet<>();
        for (int i : nums2) {
            if (firstNums.contains(i) && !secondNums.contains(i)) {
                secondNums.add(i);
                result[index++] = i;
            }
        }

        return Arrays.copyOfRange(result, 0, index);
    }

    public static void main(String[] args) {
        int[] nums1 = new int[]{1, 2, 2, 1}, nums2 = new int[]{2, 2};
        for (int i : intersection(nums1, nums2)) {
            System.out.print(i + " ");
        }
    }
}
